import { ref, reactive } from 'vue';

// 全局状态，所有组件共享
const downloadState = reactive({
    visible: false,
    progress: 0,
    fileName: '',
    downloadedSize: 0,
    totalSize: 0,
    status: 'downloading', // downloading, completed, error, cancelled
    currentTask: null,
});

const downloadQueue = ref([]);
const isDownloading = ref(false);

// 格式化文件大小
const formatFileSize = bytes => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 处理下一个下载任务
const processNextDownload = () => {
    if (downloadQueue.value.length > 0) {
        const nextTask = downloadQueue.value.shift();
        startDownload(nextTask.url, nextTask.fileName);
    }
};

// 开始下载
const startDownload = (url, fileName = '') => {
    // #ifdef APP-PLUS
    if (isDownloading.value) {
        // 如果正在下载，添加到队列
        downloadQueue.value.push({ url, fileName });
        return;
    }

    isDownloading.value = true;
    downloadState.visible = true;
    downloadState.progress = 0;
    downloadState.fileName = fileName || '未知文件';
    downloadState.downloadedSize = 0;
    downloadState.totalSize = 0;
    downloadState.status = 'downloading';

    downloadState.currentTask = uni.downloadFile({
        url,
        success: res => {
            console.log('下载成功:', res);
            downloadState.status = 'completed';
            downloadState.progress = 100;

            // 延迟关闭弹窗
            setTimeout(() => {
                downloadState.visible = false;
                isDownloading.value = false;
                processNextDownload();
            }, 1500);
        },
        fail: err => {
            console.error('下载失败:', err);
            downloadState.status = 'error';

            uni.showToast({
                title: '下载失败',
                icon: 'error',
                duration: 2000,
            });

            setTimeout(() => {
                downloadState.visible = false;
                isDownloading.value = false;
                processNextDownload();
            }, 2000);
        },
    });

    // 监听下载进度
    downloadState.currentTask.onProgressUpdate(res => {
        console.log('下载进度:', res);
        downloadState.progress = res.progress;
        downloadState.downloadedSize = res.totalBytesWritten;
        downloadState.totalSize = res.totalBytesExpectedToWrite;
    });
    // #endif
};

// 取消下载
const cancelDownload = () => {
    // #ifdef APP-PLUS
    if (downloadState.currentTask) {
        downloadState.currentTask.abort();
        downloadState.status = 'cancelled';

        setTimeout(() => {
            downloadState.visible = false;
            isDownloading.value = false;
            processNextDownload();
        }, 1000);
    }
    // #endif
};

// 获取状态文本
const getStatusText = () => {
    switch (downloadState.status) {
        case 'downloading':
            return '正在下载...';
        case 'completed':
            return '下载完成';
        case 'error':
            return '下载失败';
        case 'cancelled':
            return '已取消';
        default:
            return '准备中...';
    }
};

// useDownload hook
export const useDownload = () => {
    return {
        downloadState,
        downloadQueue,
        isDownloading,
        startDownload,
        cancelDownload,
        formatFileSize,
        getStatusText,
    };
};
